package com.qf.mybatis01.utils;


import com.qf.mybatis01.entity.Book;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class BookReader {

    /*
    * 每次调用readBatch方法时默认1000
    * */
    private Integer batchNum = 1000;

    private String filepath;

    private BufferedReader bufferedReader;

    public BookReader(String filepath) throws FileNotFoundException {
        this.filepath = filepath;

        this.bufferedReader = new BufferedReader(new FileReader(filepath));
    }

    public BookReader(Integer batchNum, String filepath) throws FileNotFoundException {
        this.batchNum = batchNum;
        this.filepath = filepath;
        this.bufferedReader = new BufferedReader(new FileReader(filepath));
    }

    public List<Book> readbatch() throws IOException {

        ArrayList<Book> books = new ArrayList<>();

        BufferedReader reader = new BufferedReader(new FileReader(filepath));

        String line = null;
        while ((line = reader.readLine())!=null){

            Book book = Book.csvToBook(line);
            books.add(book);

            if (books.size()==batchNum){
                return books;
            }
        }

        return books;
    }

    public void close() throws IOException {

        this.bufferedReader.close();

    }
}
